﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace SynchronizationContextTest
{
    class Program
    {
        static SynchronizationContext context;
        static void Main(string[] args)
        {
            //context = SynchronizationContext.Current;
            context = new SynchronizationContext();

            Console.WriteLine("主线程ID：" + Thread.CurrentThread.ManagedThreadId);
            TestThread();
            Thread.Sleep(6000);
            Console.WriteLine("主线程执行");
            context.Send(EventMethod, "Send1");
            context.Post(EventMethod, "Post2");
            context.Post(EventMethod, "Post3");
            context.Post(EventMethod, "Post4");
            context.Post(EventMethod, "Post5");
            context.Post(EventMethod, "Post6");
            context.Post(EventMethod, "Post7");

            Console.WriteLine("主线程结束");
            Console.ReadKey();
        }

        static void TestThread()
        {
            var thrd = new Thread(Start);
            thrd.Start();
        }

        static void Start()
        {
            Console.WriteLine("子线程开始运行id:" + Thread.CurrentThread.ManagedThreadId);
            if (context == null)
            {
                Console.WriteLine("context == null");
                return;
            }
            context.Send(EventMethod, "子线程Send");
            context.Post(EventMethod, "子线程Post");
            context.Post(EventMethod, "Post子1");
            context.Post(EventMethod, "Post子2");
            context.Post(EventMethod, "Post子3");

            Console.WriteLine("子线程结束");
        }

        static void EventMethod(object arg)
        {
            Console.WriteLine("CallBack::当前线程id:" + Thread.CurrentThread.ManagedThreadId + "    arg:" + (string)arg);
        }
    }
}
